package com.song.controller;

import com.song.pojo.Adminrole;
import com.song.pojo.Admins;
import com.song.pojo.ResultVO;
import com.song.service.AdminroleService;
import com.song.service.AdminsService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

/**管理员的控制层
 * @author song
 */
@Controller
@ResponseBody
@RequestMapping("admin")
public class AdminsController {
    @Resource
    private AdminsService adminsService;
    @Resource
    private AdminroleService adminroleService;

    /**
     * 管理员登录
     * @param loginName
     * @param adminPwd
     * @param request
     * @return
     */
    @RequestMapping(value = "login/{name}/{password}",method = RequestMethod.GET)
    public ResultVO<Admins> login(@PathVariable("name") String loginName, @PathVariable("password") String adminPwd, HttpServletRequest request){
        List<Admins> admins = adminsService.login(loginName, adminPwd);
        if (admins.size() > 0){
            for (Admins admin : admins) {
                if (admin != null){
                    //保存登录管理员的信息
                    request.getSession().setAttribute("admin",admin);
                    return new ResultVO<>(admin);
                }
            }
        }
        return new ResultVO<>(500,"用户名或密码不正确");
    }

    /**
     * 查询管理员角色
     * @param roleId
     * @return
     */
    @RequestMapping(value="role/{id}",method = RequestMethod.GET)
    public ResultVO<Adminrole> loginRole(@PathVariable("id") Integer roleId){
        Adminrole adminrole = adminroleService.queryByroleId(roleId);
        if (adminrole != null){
            return new ResultVO<>(adminrole);
        }
        return new ResultVO<>(500,"管理员还没有匹配角色");
    }

    @RequestMapping(value="loginOut",method = RequestMethod.GET)
    public ResultVO loginOut(HttpServletRequest request){
        //清除session中数据
        HttpSession session = request.getSession();
        session.invalidate();
        return new ResultVO<>();
    }

}
